package com.qingcloud.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingcloud.task.mapper.TaskUserMapper;
import com.qingcloud.task.model.TaskUser;
import com.qingcloud.task.service.TaskUserService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhengjibin
 * @since 2022-01-20
 */
@Service
public class TaskUserServiceImpl extends ServiceImpl<TaskUserMapper, TaskUser> implements TaskUserService {
    @Resource
    private TaskUserMapper taskUserMapper;

    @Override
    public void saveUser(List<String> userIds, Long taskId) {
        if (CollectionUtils.isEmpty(userIds)){
            return;
        }
        List<TaskUser> taskUsers = new ArrayList<>(userIds.size());
        userIds.forEach(id -> {
            TaskUser user = new TaskUser();
            user.setTaskId(taskId);
            user.setUserId(id);
            taskUsers.add(user);
        });

        saveBatch(taskUsers);
    }

    @Override
    public void updateUser(Long taskId, String toUserId) {
        TaskUser taskUser = selectByTaskId(taskId);
        if (taskUser == null){
            throw new RuntimeException("执行人不存在");
        }
        taskUser.setUserId(toUserId);
        taskUserMapper.updateById(taskUser);
    }

    @Override
    public TaskUser selectByTaskId(Long taskId) {
        QueryWrapper<TaskUser> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id",taskId);
        TaskUser taskUser = taskUserMapper.selectOne(wrapper);
        return taskUser;
    }
}
